<template>
  <a-spin :spinning="confirmLoading">
    <a-row v-if="innerVisible">
      <a-col :span="12">
        <a-form-item label="二维码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a @click.stop.prevent="download" id="qrcode" ref="qrcode" title="点击下载" />
        </a-form-item>
<!--        <div style="padding-right: 24px" v-if="innerVisible">-->
<!--          -->
<!--        </div>-->
      </a-col>

    </a-row>
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-item label="规则" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
              <j-dict-select-tag type="list" v-decorator="['ruleId', validatorRules.ruleId]" :trigger-change="true"
                                 @change="changeRuleId" dictCode="rv_report_rule,name,id" placeholder="请选择规则"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="报告编号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['reportNo', validatorRules.reportNo]" placeholder="请输入报告编号" disabled></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="年份季度" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['annualQuarter', validatorRules.annualQuarter]" placeholder="请输入年份季度"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['entrustingProject', validatorRules.entrustingProject]"
                       placeholder="请输入项目名称"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="行业类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['industryType']" placeholder="请输入行业类别"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目业主" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['entrustingCompany', validatorRules.entrustingCompany]"
                       placeholder="请输入项目业主"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目性质" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['projectNature']" placeholder="请输入项目性质"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="项目地址" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
              <a-input v-decorator="['projectAddress']" placeholder="请输入项目地址"></a-input>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="项目简介" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
              <a-textarea v-decorator="['projectDescription']" rows="4" placeholder="请输入项目简介"/>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="评价机构" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['evaluationCriterion']" placeholder="请输入评价机构"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="机构负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['organizationLeader']" placeholder="请输入机构负责人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="技术负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['technicalDirector']" placeholder="请输入技术负责人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="过程控制负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['processControlSupervisor']" placeholder="请输入过程控制负责人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目评价组长" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['projectEvaluationLeader']" placeholder="请输入项目评价组长"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="报告编制人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['reportMaker']" placeholder="请输入报告编制人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="报告审核人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['reportVerifier']" placeholder="请输入报告审核人"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目安全评价师" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['projectSafetyEvaluator']" placeholder="请输入项目安全评价师"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="参与评价工作的注册安全工程师、技术专家" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
              <a-textarea v-decorator="['participant']" rows = "5" placeholder="请输入参与评价工作的注册安全工程师、技术专家"></a-textarea>
            </a-form-item>
          </a-col>
        </a-row>
        <a-col :span="12">
          <a-form-item label="合同签订时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date placeholder="请选择合同签订时间" v-decorator="['contractSignDate']" :trigger-change="true"
                    style="width: 100%"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="提交报告时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
            <j-date placeholder="请选择提交报告时间" v-decorator="['reportCommitDate']" :trigger-change="true"
                    style="width: 100%"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="安全评价类型" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
            <a-input v-decorator="['evaluationSafetyType']" placeholder="请输入安全评价类型"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="到现场开展评价活动人员" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
            <a-textarea v-decorator="['sceneEvaluationPerson']" rows = "4" placeholder="请输入到现场开展评价活动人员"></a-textarea>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="到现场开展评价活动时间" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
            <j-date placeholder="请选择到现场开展评价活动时间"  v-decorator="['sceneEvaluationDate']" :trigger-change="true"
                    style="width: 100%"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="评价机构认为需要公开的其他信息" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
            <a-textarea v-decorator="['otherOpenInfo']" rows="5" placeholder="请输入评价机构认为需要公开的其他信息"></a-textarea>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="评价结论" :labelCol="labelFullCol" :wrapperCol="wrapperFullCol">
            <a-textarea v-decorator="['evaluationConclusion']" rows="4" placeholder="请输入评价结论"></a-textarea>
          </a-form-item>
        </a-col>
        <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
          <a-button @click="submitForm">提 交</a-button>
        </a-col>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

  import {httpAction, getAction, putAction} from '@/api/manage'
  import pick from 'lodash.pick'
  import {validateDuplicateValue} from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import JDate from '@/components/jeecg/JDate'
  import JDictSelectTag from "@/components/dict/JDictSelectTag"
  import QRCode from 'qrcodejs2'

  const ruleBaseURL = '/sys/fillRule/executeRuleByCode/'
  export default {
    name: 'RvQrcodeForm',
    components: {
      JFormContainer,
      JDate,
      JDictSelectTag,
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: () => {
        },
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data() {
      return {
        form: this.$form.createForm(this),
        innerVisible: false, //二维码展示
        qr: null,
        model: {},
        labelCol: {
          xs: {span: 12},
          sm: {span: 6},
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16},
        },
        labelFullCol: {
          xs: {span: 12},
          sm: {span: 3},
        },
        wrapperFullCol: {
          xs: {span: 24},
          sm: {span: 20},
        },
        smallCol: {
          xs: {span: 8},
          sm: {span: 6},
        },
        confirmLoading: false,
        validatorRules: {
          ruleId: {
            rules: [
              {required: true, message: '请输入规则!'},
              {max: 36, message: '输入内容过长'}
            ]
          },
          annualQuarter: {
            rules: [
              {required: true, message: '请输入报告编号!'},
              {max: 15, message: '输入内容过长'}
            ]
          },
          reportNo: {
            rules: [
              {required: true, message: '请输入报告编号!'},
              {max: 36, message: '输入内容过长'}
            ]
          },
          entrustingCompany: {
            rules: [
              {required: true, message: '请输入项目业主!'},
            ]
          },
          entrustingProject: {
            rules: [
              {required: true, message: '请输入项目名称!'},
            ]
          },
          isInvalid: {
            rules: [
              {required: false},
              {pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},
            ]
          },
          isQrcodeGen: {
            rules: [
              {required: false},
              {pattern: /^-?\d+\.?\d*$/, message: '请输入数字!'},
            ]
          },
        },
        url: {
          add: "/demo/rvQrcode/add",
          edit: "/demo/rvQrcode/edit",
          queryById: "/demo/rvQrcode/queryById",
          rule: {
            reportNo: ruleBaseURL + 'ReportNumberRule'
          },
        }
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created() {
      //如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      changeRuleId(v) {
        this.getReportNo(v);
      },
      // 展示二维码
      payOrder(reportNo) {

        if (reportNo) {
          this.innerVisible = true
          // 二维码内容,一般是由后台返回的跳转链接,这里是写死的一个链接
          // this.qrcode = 'https://www.faith-safety.com/reportVerfication/report.html?reportNo=' + reportNo+""
          this.qrcode = 'http://www.faith-safety.com:8080/h5/report.html?reportNo=' + reportNo + ""
          // 使用$nextTick确保数据渲染
          this.$nextTick(() => {
            this.createQrcode()
          })
        } else {
          this.innerVisible = false
          this.$message.warning("表单不存在");
        }
      },
      // 生成二维码
      createQrcode() {
        this.qr = new QRCode('qrcode', {
          width: 90,
          height: 90, // 高度
          text: this.qrcode, // 二维码内容
        })
        this.qr._el.title='点击下载二维码'
        // console.log(this.qrcode)
      },
      // 关闭弹框,清除已经生成的二维码
      close() {
        if (this.$refs.qrcode) {
          this.$refs.qrcode.innerHTML = ''
        }

      },
      getReportNo(v) {
        let params = {
          ruleId: v
        }
        putAction(this.url.rule.reportNo, params).then(res => {
          console.log(res)
          // 执行成功，获取返回的值，并赋到页面上
          if (res.success) {
            this.form.setFieldsValue({"reportNo": res.result})
          }
        })
      },
      add() {
        this.edit({});
      },
      download() {
        const imgUrl = this.qrcode;
// 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
        if (window.navigator.msSaveOrOpenBlob) {
          var bstr = atob(imgUrl.split(',')[1])
          var n = bstr.length
          var u8arr = new Uint8Array(n)
          while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
          }
          var blob = new Blob([u8arr])
          window.navigator.msSaveOrOpenBlob(blob, this.form.getFieldValue('entrustingProject')+'-'+this.form.getFieldValue('reportNo') + '.png')
        } else {
          // 这里就按照chrome等新版浏览器来处理
          let qrCodeEle = document.getElementById('qrcode').getElementsByTagName('canvas');
          const a = document.createElement('a')
          a.href = qrCodeEle[0].toDataURL('image/png')
          a.setAttribute('download', this.form.getFieldValue('entrustingProject')+'-'+this.form.getFieldValue('reportNo'))
          a.click();
        }
      },
      edit(record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'ruleId', 'reportNo', 'entrustingCompany', 'annualQuarter', 'entrustingProject', 'industryType', 'projectNature', 'projectAddress', 'projectDescription', 'evaluationCriterion', 'organizationLeader', 'technicalDirector', 'processControlSupervisor', 'projectEvaluationLeader', 'reportMaker', 'reportVerifier', 'projectSafetyEvaluator', 'participant', 'contractSignDate', 'reportCommitDate', 'evaluationSafetyType', 'sceneEvaluationPerson', 'sceneEvaluationDate', 'otherOpenInfo', 'evaluationConclusion'))
          let reportNo = this.model.reportNo;
          if (reportNo) {
            this.payOrder(reportNo);
          }
        })
      },
      //渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = {id: this.formData.dataId};
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      submitForm() {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if (!this.model.id) {
              httpurl += this.url.add;
              method = 'post';
            } else {
              httpurl += this.url.edit;
              method = 'put';
            }
            let formData = Object.assign(this.model, values);
            console.log("表单提交数据", formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }

        })
      },
      popupCallback(row) {
        this.form.setFieldsValue(pick(row, 'ruleId', 'reportNo', 'annualQuarter', 'entrustingCompany', 'entrustingProject', 'industryType', 'projectNature', 'projectAddress', 'projectDescription', 'evaluationCriterion', 'organizationLeader', 'technicalDirector', 'processControlSupervisor', 'projectEvaluationLeader', 'reportMaker', 'reportVerifier', 'projectSafetyEvaluator', 'participant', 'contractSignDate', 'reportCommitDate', 'evaluationSafetyType', 'sceneEvaluationPerson', 'sceneEvaluationDate', 'otherOpenInfo', 'evaluationConclusion'))
      },
    }
  }
</script>
<style type="text/css">
  .ant-form-item-label {
    display: inline-block;
    overflow: hidden;
    line-height: 39.9999px;
    /*white-space: nowrap;*/
    white-space: pre-line;
    text-align: right;
    vertical-align: middle;
    padding-right: 3px;
  }


</style>